/**
 *
 * @param {Array} array
 * @param {*} id
 * @param {*} pid
 * @returns {Array}
 */
export const listToTree = function (array = [], id = 'id', pid = 'pid') {
  let listMap = {}
  let tree: Array<{ chileren: any; [key: string]: any }> = []

  for (const e of array) {
    listMap[e[id]] = e
    if (e[pid] === 0) {
      tree.push(e)
    }
  }

  for (let i = 0, len = array.length; i < len; i++) {
    if (array[i][pid] === 0) continue

    let p: any = listMap[array[i][pid]]
    if (p.children) {
      p.children.push(array[i])
    } else {
      p.children = [array[i]]
    }
  }

  return { tree, listMap }
}
